# -*- encoding=utf-8 -*-
import json
import ssl
import logging
from urllib import request, parse
from utils.configReader import myconfigReader

#取消ssl请求的证书验证
ssl._create_default_https_context = ssl._create_unverified_context

class ConfigReader(object):
    def __init__(self):
        self.baseUrl = myconfigReader.base_url
        return;

    def getToken(self):
        # corpid = self.config.get("wx", "corpid")
        corpid = myconfigReader.corpid
        # secret = self.config.get("wx", "secret")
        secret = myconfigReader.secret
        # url = self.getBaseUrl()
        url = myconfigReader.base_url
        url = url.replace("${corpid}", corpid)
        url = url.replace("${secret}", secret)
        with request.urlopen(url) as f:
            data = f.read()
            ret = json.loads(data.decode('utf-8'))
            return ret['access_token']

    def getBaseUrl(self):
        return self.baseUrl

    def getSendMsgUrl(self):
        # url = self.config.get("wx", "send_msg_url")
        url = myconfigReader.send_msg_url
        token = self.getToken()
        url = url.replace("${ACCESS_TOKEN}", token)
        return url

    def get_get_user_url(self, code):
        url = myconfigReader.get_wechat_id_url
        token = self.getToken()
        url = url.replace("${ACCESS_TOKEN}", token)
        url = url.replace("${CODE}", code)
        return url


class WxClient(object):
    def __init__(self):
        self.logger = logging.getLogger(__name__)
        self.logger.info('initialize wechat configuration...')
        self.configReader = ConfigReader()
        self.logger.info('Done.')
        self.baseUrl = self.configReader.getBaseUrl()

    # 添加一条售后服务信息
    def addNewService(self, toUser, toParty=None, content="无内容", agentid = 12):
        url = self.configReader.getSendMsgUrl()
        msg = {
            "msgtype" : "text",
            "agentid" : agentid,
            "text": {
                "content": content
            }
        }
        if toUser is not None:
            msg['touser'] = toUser
        if toParty is not None:
            msg['toparty'] = toParty

        msg = json.dumps(msg, ensure_ascii=False)
        msg = msg.encode('utf-8')

        req = request.Request(url)
        with request.urlopen(req, data=msg) as f:
            # print('Status:', f.status, f.reason)
            # for k, v in f.getheaders():
            #     print('%s: %s' % (k, v))
            data = f.read().decode('utf-8')
            ret = json.loads(data)
            if ret['errmsg'] == 'ok':
                return True
            return False

    def get_wechat_id_by_code(self,code):
        url = self.configReader.get_get_user_url(code)
        req = request.Request(url)
        with request.urlopen(req) as f:
            data = f.read().decode('utf-8')
            ret = json.loads(data)
            if 'UserId' in ret:
                return ret['UserId']
            return None



